#include "resetdialog.h"
#include "ui_resetdialog.h"
#include <QRegularExpression>

#include "httpmgr.h"

ResetDialog::ResetDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ResetDialog)
{
    ui->setupUi(this);
    connect(ui->user_edit,&QLineEdit::editingFinished,this,[this](){
        checkUserValid();
    });
    connect(ui->email_edit,&QLineEdit::editingFinished,this,[this](){
        checkEmailValid();
    });
    connect(ui->pwd_edit,&QLineEdit::editingFinished,this,[this](){
        checkPassValid();
    });
    connect(ui->user_edit,&QLineEdit::editingFinished,this,[this](){
        checkVerifyValid();
    });
    initHandlers();


    ui->pwd_edit->setEchoMode(QLineEdit::Password);
    //连接httpMgr信号
    connect(HttpMgr::GetInstance().get(),&HttpMgr::sig_reset_mod_finish,
                                    this,&ResetDialog::slot_reset_mod_finish);

}

ResetDialog::~ResetDialog()
{
    delete ui;
}


bool ResetDialog::checkEmailValid()
{
    //验证邮箱的地址正则表达式
    auto email = ui->email_edit->text();
    // 邮箱地址的正则表达式
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match = regex.match(email).hasMatch(); // 执行正则表达式匹配
    if(!match){
        //提示邮箱不正确
        AddTipErr(TipErr::TIP_EMAIL_ERR, tr("邮箱地址不正确"));
        return false;
    }
    DelTipErr(TipErr::TIP_EMAIL_ERR);
    return true;
}
bool ResetDialog::checkVerifyValid()
{
    auto pass = ui->verify_edit->text();
    if(pass.isEmpty()){
        AddTipErr(TipErr::TIP_VARIFY_ERR, tr("验证码不能为空"));
        return false;
    }
    DelTipErr(TipErr::TIP_VARIFY_ERR);
    return true;
}

bool ResetDialog::checkUserValid()
{
    if(ui->user_edit->text() == ""){
        AddTipErr(TipErr::TIP_USER_ERR, tr("用户名不能为空"));
        return false;
    }
    DelTipErr(TipErr::TIP_USER_ERR);
    return true;
}

bool ResetDialog::checkPassValid()
{
    auto pass = ui->pwd_edit->text();
    if(pass.length()<6||pass.length()>15)
    {
        //提示密码长度应在[6-15]以内
        AddTipErr(TipErr::TIP_PWD_ERR,"密码长度应为[6-15]");
        return false;
    }
    //同时密码的组成应符合正则表达式
    QRegularExpression regExp("^[a-zA-Z0-9!@#$%^&*]{6,15}$");
    bool match = regExp.match(pass).hasMatch();
    if(!match){
        //提示字符非法
        AddTipErr(TipErr::TIP_PWD_ERR, tr("不能包含非法字符"));
        return false;;
    }
    DelTipErr(TipErr::TIP_PWD_ERR);
    return true;
}





void ResetDialog::AddTipErr(TipErr te,QString tips)
{
    _tip_errs[te]=tips;
    showTip(tips,false);
}

void ResetDialog::DelTipErr(TipErr te)
{
    _tip_errs.remove(te);
    if(!_tip_errs.empty())
    {
        showTip(_tip_errs.first(),false);
        return;
    }
    showTip("",true);
}
void ResetDialog::showTip(QString tips,bool b_ok)
{
    ui->err_tip->setText(tips);
    if(b_ok)
    {

        ui->err_tip->setProperty("state","normal");
    }
    else
    {
        ui->err_tip->setProperty("state","err");
    }

    repolish(ui->err_tip);
}

void ResetDialog::initHandlers()
{
    _handlers[ReqId::ID_RESET_PWD]=std::bind(&ResetDialog::ResetPassword,this,std::placeholders::_1);
    _handlers[ReqId::ID_GET_VERIFY_CODE] = std::bind(&ResetDialog::GetVerifyCode,this,std::placeholders::_1);
}

void ResetDialog::GetVerifyCode(const QJsonObject &obj)
{
    if(obj["error"].toInt()!=ErrorCodes::SUCCESS)
    {
        showTip("参数错误",false);
        return;
    }
    QString email = obj["email"].toString();
    showTip("验证码已发送至邮箱，请查收",true);
    qDebug()<<">>email is "<<email;

}

void ResetDialog::ResetPassword(const QJsonObject &obj)
{
    if(obj["error"].toInt()!=ErrorCodes::SUCCESS)
    {
        showTip("参数错误",false);
        return;
    }
    QString email = obj["email"].toString();
    QString user = obj["user"].toString();
    showTip("密码重置成功，点击返回登陆",true);
    qDebug()<<">>email is "<<email<<" user is "<<user;

    return;
}

void ResetDialog::slot_reset_mod_finish(ReqId req_id, QString res, ErrorCodes err)
{
    if(err!=ErrorCodes::SUCCESS)
    {
        qDebug()<<"slot_reset_mod_finish failed";
        return;
    }
    //res转化为json
    QByteArray byteArray = res.toUtf8();
    QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);

    if(jsonDoc.isNull())
    {
        showTip("",false);
        return;
    }
    if(!jsonDoc.isObject())
    {
        showTip("",false);
        return;
    }

    QJsonObject jsonObj = jsonDoc.object();
    _handlers[req_id](jsonObj);
}

void ResetDialog::on_verify_btn_clicked()
{
    //获取邮箱账号，然后将邮箱账号上传到后端
    qDebug()<<"receive verify btn clicked\n";
    auto email = ui->email_edit->text();
    bool ret = checkEmailValid();
    if(!ret)
    {
        return;
    }
    QJsonObject json;
    json["email"]= email;
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/get_verifycode"),json,ReqId::ID_GET_VERIFY_CODE,Modules::RESETMOD);
}


void ResetDialog::on_sure_btn_clicked()
{
    //检查提交信息的正确性
    bool valid = checkUserValid();
    if(!valid){
        return;
    }
    valid = checkEmailValid();
    if(!valid){
        return;
    }
    valid = checkPassValid();
    if(!valid){
        return;
    }
    valid = checkVerifyValid();
    if(!valid){
        return;
    }
    QJsonObject json;
    json["user"]= ui->user_edit->text();
    json["email"] = ui->email_edit->text();
    json["passwd"]=ui->pwd_edit->text();
    json["verifycode"]=ui->verify_edit->text();

    HttpMgr::GetInstance()->PostHttpReq(gate_url_prefix+"/reset_pwd",json,ReqId::ID_RESET_PWD,Modules::RESETMOD);
}


void ResetDialog::on_return_btn_clicked()
{
    //发送信号
    emit switchLogin();
}

